<template>
  <validate-form @form-submit="onFormSubmit">
    <div class="mb-3">
      <label for="exampleInputEmail1" class="form-label">邮箱地址</label>
      <validate-input
        :rules="emailRules"
        v-model="emailVal"
        placeholder="xxx@xxx.com"
        type="email"
      />
    </div>
    <div class="mb-3">
      <label for="exampleInputPassword1" class="form-label">密码</label>
      <validate-input
        :rules="passwordRules"
        v-model="passwordVal"
        placeholder="password"
        type="password"
      />
    </div>
    <template #submit>
      <button type="submit" class="btn btn-primary btn-block btn-large">
        登录
      </button>
    </template>
  </validate-form>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import validateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import createMessage from '../components/createMessage'
export default defineComponent({
  name: 'Login',
  components: {
    validateInput,
    ValidateForm
  },
  setup() {
    const router = useRouter()
    const emailVal = ref('')
    const emailRules: RulesProp = [
      { type: 'require', message: '电子邮箱地址不能为空' },
      { type: 'email', message: '请输入正确的电子邮箱格式' },
      { type: 'range', message: '输入的字符必须大于3并且小于25' }
    ]
    const passwordVal = ref('')
    const passwordRules: RulesProp = [
      { type: 'require', message: '密码不能为空' }
    ]
    const store = useStore()
    const onFormSubmit = (result: boolean) => {
      if (result) {
        // 返回首页并触发新的方法login登录
        const payload = {
          email: emailVal.value,
          password: passwordVal.value
        }
        // 两步：第一步是登录第二步是fetch数据
        store
          .dispatch('loginAndFetch', payload)
          .then(() => {
            createMessage('登录成功，2秒之后跳转首页', 'success')
            setTimeout(() => {
              router.push('/')
            }, 2000)
          })
          .catch((e) => {
            console.log(e)
          })
      }
    }
    return {
      emailRules,
      emailVal,
      passwordVal,
      passwordRules,
      onFormSubmit
    }
  }
})
</script>
